<template>
  <child-page>
    <a-tabs defaultActiveKey="1">
      <a-tab-pane key="1">
        <span slot="tab">
          <a-icon type="project" />
          基本参数
        </span>
        <div class="components-form-demo-advanced-search">
          <a-form
            class="ant-advanced-search-form"
            :form="form"
            @submit="handleSubmit"
          >
            <a-form-item v-bind="formItemLayout" label="用户名">
              <a-input
                disabled
                v-decorator="[
                  'nickName',
                  { initialValue: initInfo.username, rules: rule.nickName }
                ]"
              />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="姓名">
              <a-input
                v-decorator="[
                  'true_name',
                  { initialValue: initInfo.true_name, rules: rule.userName }
                ]"
              />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="手机号">
              <a-input
                v-decorator="[
                  'mobile',
                  { initialValue: initInfo.mobile, rules: rule.phone }
                ]"
              />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="头像">
              <div
                class="avatar-wrapper"
                @click="showUploadModal"
                style="width: 122px"
              >
                <img
                  v-if="initInfo.avatar"
                  :src="$api.picPre + initInfo.avatar"
                  alt=""
                  width="100px"
                  height="100px"
                />
                <a-avatar v-else :size="100" icon="user" />
                <div class="modal">
                  <a-icon type="plus"></a-icon>
                </div>
              </div>
              <hry-upload
                field="file"
                @crop-success="cropSuccess"
                @crop-upload-success="cropUploadSuccess"
                @crop-upload-fail="cropUploadFail"
                @src-file-set="srcFileSet"
                v-model="visible"
                :width="100"
                :height="100"
                :url="$api.upload"
                :params="params"
                img-format="png"
              ></hry-upload>
            </a-form-item>
            <a-row>
              <a-col :span="24" :style="{ textAlign: 'center' }">
                <a-button type="primary" html-type="submit">
                  提交
                </a-button>
                <a-button :style="{ marginLeft: '8px' }" @click="handleReset">
                  重置
                </a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-tab-pane>
      <a-tab-pane key="2">
        <span slot="tab">
          <a-icon type="project" />
          修改密码
        </span>
        <div class="components-form-demo-advanced-search">
          <a-form
            class="ant-advanced-search-form"
            :form="pswForm"
            @submit="handleChangePsw"
          >
            <a-form-item v-bind="formItemLayout" label="密码">
              <a-input
                type="password"
                v-decorator="[
                  'password',
                  {
                    rules: [
                      { required: true, message: '必填项' },
                      { validator: validateToNextPassword }
                    ]
                  }
                ]"
              />
            </a-form-item>
            <a-form-item v-bind="formItemLayout" label="确认密码">
              <a-input
                type="password"
                v-decorator="[
                  'repassword',
                  {
                    rules: [
                      { required: true, message: '必填项' },
                      { validator: compareToFirstPassword }
                    ]
                  }
                ]"
                @blur="handleConfirmBlur"
              />
            </a-form-item>
            <a-row>
              <a-col :span="24" :style="{ textAlign: 'center' }">
                <a-button type="primary" html-type="submit">
                  提交
                </a-button>
                <a-button
                  :style="{ marginLeft: '8px' }"
                  @click="handleResetPsd"
                >
                  重置
                </a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-tab-pane>
    </a-tabs>
  </child-page>
</template>

<script>
import childPage from "@/components/childPageContent/index";
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
}
// const root = process.env.VUE_APP_API_ROOT;
import validate from "@/tool/validateFunction";
import { Avatar } from "ant-design-vue";
import hryUpload from "vue-image-crop-upload";
import { getToken } from "@/tool/qiniu";
export default {
  name: "add",
  components: {
    aAvatar: Avatar,
    hryUpload: hryUpload,
    childPage
  },
  data() {
    return {
      form: this.$form.createForm(this),
      pswForm: this.$form.createForm(this),
      visible: false,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 }
        }
      },
      athList: [],
      statusOption: [{ label: "在用", value: 1 }, { label: "停用", value: 2 }],
      sexOption: [{ label: "男", value: 1 }, { label: "女", value: 2 }],
      rule: {
        nickName: [
          { required: true, message: "必填项" },
          { validator: validate.validateLength, max: 15, min: 1 }
        ],
        password: [{ required: true, message: "必填项" }],
        checkPsw: [{ required: true, message: "必填项" }],
        userName: [{ required: true, message: "必填项" }],
        email: [{ validator: validate.validateEmail }],
        phone: [{ validator: validate.validatePhoneNumber }],
        status: [{ required: true, message: "必填项" }],
        sex: [{ required: true, message: "必填项" }]
      },
      initInfo: {
        status: 1
      },
      imageUrl: "",
      params: {
        token: ""
      },
      loading: false,
      id: ""
    };
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault();
      this.form.validateFields((error, values) => {
        if (!error) {
          values.avatar = this.initInfo.avatar;
          values.id = this.id;
          delete values.nickName;
          this.$ajax
            .post(this.$api.userInfoEdit, values)
            .then(() => {
              this.$notification.success({
                message: "编辑成功！"
              });
              this.$router.push({ name: "authorityUser" });
            })
            .catch(err => {
              this.$notification.error({
                message: err
              });
            });
        } else {
          return false;
        }
      });
    },
    handleChangePsw(e) {
      e.preventDefault();
      this.pswForm.validateFields((error, values) => {
        if (!error) {
          values.id = this.$route.params.id;
          this.$ajax
            .post(this.$api.modifyPassword, values)
            .then(() => {
              if (values.id - 0 === this.$store.state.userInfo.id) {
                this.$ajax
                  .post(this.$api.logout, values)
                  .then(() => {
                    this.$notification.success({
                      message: "密码修改成功，请重新登录！"
                    });
                    this.$router.push({ name: "adminLogin" });
                  })
                  .catch(err => {
                    this.$notification.error({
                      message: err
                    });
                  });
              } else {
                this.$notification.success({
                  message: "密码修改成功！"
                });
                this.$router.push({ name: "authorityUser" });
              }
            })
            .catch(err => {
              this.$notification.error({
                message: err
              });
            });
        } else {
          return false;
        }
      });
    },
    handleConfirmBlur(e) {
      const value = e.target.value;
      this.confirmDirty = this.confirmDirty || !!value;
    },
    validateToNextPassword(rule, value, callback) {
      const form = this.pswForm;
      if (value && this.confirmDirty) {
        form.validateFields(["repassword"], { force: true });
      }
      callback();
    },
    compareToFirstPassword(rule, value, callback) {
      const form = this.pswForm;
      if (value && value !== form.getFieldValue("password")) {
        callback("两次密码不一致!");
      } else {
        callback();
      }
    },
    handleReset() {
      this.form.resetFields();
    },
    handleResetPsd() {
      this.pswForm.resetFields();
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e;
      }
      return e && e.fileList;
    },
    handleChange(info) {
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
      if (info.file.status === "done") {
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl;
          this.loading = false;
        });
      }
    },
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg";
      if (!isJPG) {
        this.$notification.error({
          message: "You can only upload JPG file!"
        });
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$notification.error({
          message: "Image must smaller than 2MB!"
        });
      }
      return isJPG && isLt2M;
    },
    cropSuccess(imgDataUrl) {
      this.imageUrl = imgDataUrl;
    },
    srcFileSet(fileName) {
      let timestamp2 = new Date().getTime();
      let typeArr = fileName.split(".");
      let type = typeArr[typeArr.length - 1];
      let savekey = "avatar/" + timestamp2 + "." + type;
      this.params.token = getToken(savekey);
    },
    showUploadModal() {
      this.visible = true;
    },
    cropUploadSuccess(jsonData) {
      this.$notification.success({
        message: "上传成功"
      });
      this.initInfo.avatar = jsonData.key;
      this.visible = false;
    },
    cropUploadFail() {
      this.$notification.error({
        message: "上传失败"
      });
    },
    getAdminById() {
      this.id = this.$route.params.id;
      this.$ajax
        .get(this.$api.getTargetUserInfo, { id: this.id })
        .then(res => {
          this.initInfo = res;
        })
        .catch(err => {
          this.$notification.error({
            message: err
          });
        });
    }
  },
  created() {
    this.getAdminById();
  }
};
</script>

<style scoped lang="less">
.components-form-demo-advanced-search {
  .flex_align_center();
}
.avatar-wrapper {
  border: 1px dashed @border-color-base;
  padding: 10px;
  position: relative;
  .modal {
    display: none;
    .anticon {
      position: absolute;
      top: 50%;
      left: 50%;
      color: #d8d8d8;
      font-size: 50px;
      transform: translate(-50%, -50%);
    }
  }
  &:hover {
    .modal {
      display: block;
      position: absolute;
      top: 0;
      left: 0;
      height: 100%;
      width: 100%;
      background: rgba(0, 0, 0, 0.6);
    }
  }
}
</style>
